package com.ben.utils.concurrent;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PerfThreadPoolExecutor extends ThreadPoolExecutor {

    private final Timer mTimer = new Timer();

    public PerfThreadPoolExecutor(
            int corePoolSize,
            int maximumPoolSize,
            long keepAliveTime,
            TimeUnit unit,
            BlockingQueue<Runnable> workQueue,
            ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public void executeDelay(final Runnable task, long delay) {
        if (delay == 0) {
            execute(task);
        } else {
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    execute(task);
                }
            };
            mTimer.schedule(timerTask, TimeUnit.MILLISECONDS.toMillis(delay));
        }
    }

    public void executeDelay(final Runnable task, long delay, final TimeUnit unit) {
        if (delay == 0) {
            execute(task);
        } else {
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    execute(task);
                }
            };
            mTimer.schedule(timerTask, unit.toMillis(delay));
        }
    }

}
